
package com.hc.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.hc.domain.CompanyPartner;
import com.hc.domain.IndexData;
import com.hc.domain.ResourcesPic;
import com.hc.service.ICompanyPartnerService;
import com.hc.service.IIndexDataService;
import com.hc.service.IResourcesPicService;
import com.hc.util.FileUtils;
import com.hc.util.IdWorker;
import com.hc.util.LoggerUtil;

@Controller
@RequestMapping("Resource")
public class ResourceController extends BaseController {

	@Resource
	private IResourcesPicService resourcesPicService;
	@Resource
	private IIndexDataService indexDataService;
	@Resource
	private ICompanyPartnerService companyPartnerService;

	/**
	 * 
	 * @Description： 获取图片list
	 * 
	 * @param req
	 * @param resp
	 * @param type
	 *            图片类型
	 * @return
	 * @author:
	 * @since: 2017年8月24日 下午3:27:03
	 */
	@ResponseBody
	@RequestMapping(value = "getPicList/{type}", method = RequestMethod.GET)
	public JSON getBannerList(HttpServletRequest req, HttpServletResponse resp, @PathVariable String type) {
		List<ResourcesPic> pics = resourcesPicService.findPicsByTypeDesc(type);
		return Message(SUCCESS, "获取数据成功", pics);
	}

	@ResponseBody
	@RequestMapping(value = "del", method = RequestMethod.POST)
	public JSON del(HttpServletRequest req, HttpServletResponse resp,
			@RequestParam(value = "resourceId", required = true) int resourceId) {
		ResourcesPic pic = resourcesPicService.getPicById(resourceId);
		if (pic == null) {
			return Message(ERROR, "该文件已删除", null);
		}
		if (pic.getStatus() == 1) {
			return Message(ERROR, "文件启用中，请先禁用", null);
		}
		resourcesPicService.delete(pic);
		return Message(SUCCESS, "删除成功", null);
	}

	/**
	 * 
	 * @Description： 存放首页数据
	 * 
	 * @param req
	 * @param resp
	 * @param id
	 * @param name
	 *            标题
	 * @param data
	 *            数据
	 * @param text
	 *            介绍
	 * @return
	 * @author:
	 * @since: 2017年8月24日 下午5:14:49
	 */
	@ResponseBody
	@RequestMapping(value = "saveData", method = RequestMethod.POST)
	public JSON saveData(HttpServletRequest req, HttpServletResponse resp,
			@RequestParam(value = "id", required = true) int id,
			@RequestParam(value = "name", required = true) String name,
			@RequestParam(value = "data", required = true) String data,
			@RequestParam(value = "text", required = true) String text) {
		if (id > 3) {
			return Message(ERROR, "操作失败", null);
		}
		if (isEmpty(name)) {
			return Message(ERROR, "标题不能为空", null);
		}
		if (isEmpty(data)) {
			return Message(ERROR, "数据不能为空", null);
		}
		if (isEmpty(text)) {
			return Message(ERROR, "介绍不能为空", null);
		}
		IndexData idata = indexDataService.getById(id);
		if (idata == null) {
			idata = new IndexData();
		}
		idata.setId(id);
		idata.setCount(data);
		idata.setType(name);
		idata.setContent(text);
		indexDataService.saveOrUpdate(idata);
		return Message(SUCCESS, "操作成功", idata);
	}

	/**
	 * 
	 * @Description： 获取首页数据
	 * 
	 * @param req
	 * @param resp
	 * @return
	 * @author:
	 * @since: 2017年8月24日 下午5:15:22
	 */
	@ResponseBody
	@RequestMapping(value = "getData", method = RequestMethod.GET)
	public JSON getData(HttpServletRequest req, HttpServletResponse resp) {
		List<IndexData> datas = indexDataService.findDatas();
		return Message(SUCCESS, "操作成功", datas);
	}

	/**
	 * 
	 * @Description： 获取合作伙伴列表
	 * 
	 * @param req
	 * @param resp
	 * @return
	 * @author:
	 * @since: 2017年8月25日 上午10:09:40
	 */
	@ResponseBody
	@RequestMapping(value = "getCompanys", method = RequestMethod.GET)
	public JSON getCompanys(HttpServletRequest req, HttpServletResponse resp) {
		List<CompanyPartner> cp = companyPartnerService.findCompanys();
		return Message(SUCCESS, "获取数据成功", cp);
	}
	/**
	 * 
	 * @Description： 新增、保存公司信息
	 * @param req
	 * @param resp
	 * @param file
	 * @param companyName
	 * @param webSite
	 * @param info
	 * @param id
	 * @return
	 * @author:  
	 * @since: 2017年8月25日 上午11:23:51
	 */
	@ResponseBody
	@RequestMapping(value = "saveOrUpdateCompany", method = RequestMethod.POST)
	public JSON saveOrUpdateCompany(HttpServletRequest req, HttpServletResponse resp,
			@RequestParam(value = "file", required = false) MultipartFile file,
			@RequestParam(value = "companyName", required = true) String companyName,
			@RequestParam(value = "webSite", required = true) String webSite,
			@RequestParam(value = "info", required = true) String info,
			@RequestParam(value = "id", required = false) int id,
			@RequestParam(value = "type", required = false) String type) {
		if (isEmpty(companyName)) {
			return Message(ERROR, "企业名称不能为空", null);
		}
		if (isEmpty(webSite)) {
			return Message(ERROR, "企业网址不能为空", null);
		}
		if (isEmpty(info)) {
			return Message(ERROR, "企业介绍不能为空", null);
		}
		String url = "";
		if (file!=null&&!file.isEmpty()) {
			String ext = "gif,jpg,jpeg,png,bmp";
			String path = req.getContextPath();
			String basePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + path + "/";
			String newFileName = IdWorker.createId();
			FileOutputStream fos = null;
			InputStream in = null;
			File f = new File(FILE_PATH + "CompanyLogo");
			if (!f.exists()) {
				f.mkdirs();
			}
			if (file.isEmpty()) {
				return Message(ERROR, "请选择文件", null);
			}
			try {
				fos = new FileOutputStream(FILE_PATH + "CompanyLogo" + "/" + newFileName);
			
			in = file.getInputStream();
			String fileExt = FileUtils.getFileTypeByStream(IOUtils.toByteArray(file.getInputStream()));
			if (isEmpty(fileExt) || ext.indexOf(fileExt) < 0) {
				return Message(ERROR, "未知图片类型（合法格式:PNG/JPEG/JPG/GIF/BMP）", null);
			}
			 if ((in.available() / 1024) > 102400) { 
				 return Message(ERROR,"上传文件大小超过限制（100KB）", null); 
			 }
			int b = 0;
			while ((b = in.read()) != -1) {
				fos.write(b);
			}
			url = basePath + "File/getFile/" + "CompanyLogo" + "/" + newFileName;
			System.err.println(url);
			} catch (Exception e) {
				return LoggerUtil.logInfo(e, "新增企业异常");
			} finally {
				try {
					if (fos != null) {
						fos.close();
					}
					if (in != null) {
						in.close();
					}
				} catch (Exception e2) {
					LoggerUtil.error(e2);
				}
			}
		}
		if (id == 0) {
			CompanyPartner cp = new CompanyPartner();
			cp.setCompanyName(companyName);
			cp.setInfo(info);
			cp.setWebSite(webSite);
			cp.setLogo(url);
			cp.setStatus(1);
			cp.setType(type);
			companyPartnerService.save(cp);
			return Message(SUCCESS, "新增成功", null);
		}
		if (id != 0) {
			CompanyPartner cp = companyPartnerService.getById(id);
			if (cp==null) {
				return Message(ERROR, "该企业不存在", null);
			}
			cp.setCompanyName(companyName);
			cp.setInfo(info);
			if ((file!=null&&!file.isEmpty())) {
				cp.setLogo(url);
			}
			cp.setStatus(1);
			cp.setWebSite(webSite);
			companyPartnerService.update(cp);
			return Message(SUCCESS, "修改成功", null);
		}
		return Message(ERROR, "未知操作", null);
	}
	/**
	 * 
	 * @Description： 删除数据
	 * @param req
	 * @param resp
	 * @param id
	 * @return
	 * @author:  
	 * @since: 2017年8月25日 下午2:15:09
	 */
	@ResponseBody
	@RequestMapping(value="delCompany",method=RequestMethod.POST)
	public JSON delCompany(HttpServletRequest req, HttpServletResponse resp,
			@RequestParam(value = "id", required = true) int id) {
		CompanyPartner cp = companyPartnerService.getById(id);
		if (cp==null) {
			return Message(ERROR, "该已数据不存在", null);
		}
		companyPartnerService.delete(cp);
		return Message(SUCCESS, "删除成功", null);
	}
	/**
	 * 
	 * @Description： 首页轮播排序
	 * @param req
	 * @param resp
	 * @param resourceId
	 * @param type
	 * @return
	 * @author:  
	 * @since: 2017年8月25日 下午2:29:40
	 */
	@ResponseBody
	@RequestMapping(value="changeSort",method=RequestMethod.POST)
	public JSON changeSort(HttpServletRequest req, HttpServletResponse resp,
			@RequestParam(value = "resourceId", required = true) int resourceId,
			@RequestParam(value = "type", required = true) String type) {
		ResourcesPic rp = resourcesPicService.getPicById(resourceId);
		if (rp==null) {
			return Message(ERROR, "该数据不存在", null);
		}
		if ("down".equals(type)) {
			rp.setSort(rp.getSort()-1);
			resourcesPicService.update(rp);
			return Message(SUCCESS, "", null);
		}
		if ("up".equals(type)) {
			rp.setSort(rp.getSort()+1);
			resourcesPicService.update(rp);
			return Message(SUCCESS, "", null);
		}
		return Message(ERROR, "未知操作", null);
	}
	/**
	 * 
	 * @Description： 改变状图片状态
	 * @param req
	 * @param resp
	 * @param resourceId
	 * @return
	 * @author:  
	 * @since: 2017年8月25日 下午2:31:15
	 */
	@ResponseBody
	@RequestMapping(value="changeStatus",method=RequestMethod.POST)
	public JSON changeStatus(HttpServletRequest req, HttpServletResponse resp,
			@RequestParam(value = "resourceId", required = true) int resourceId) {
		ResourcesPic rp = resourcesPicService.getPicById(resourceId);
		if (rp==null) {
			return Message(ERROR, "该数据不存在", null);
		}
		if (rp.getStatus()==1) {
			rp.setStatus(0);
		}else{
			rp.setStatus(1);
		}
		resourcesPicService.update(rp);
		return Message(SUCCESS, "操作成功 ", null);
	}
}
